package com.jabo.wechatmomentsdemo.http;

import android.net.ParseException;

import com.google.gson.JsonParseException;
import com.jabo.wechatmomentsdemo.R;
import com.jabo.wechatmomentsdemo.utils.StringUtil;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;

import java.net.ConnectException;

import retrofit2.HttpException;

/**
 * @anthor JZheng3
 * @Time: 2020/9/4
 */
public class ExceptionHandle {
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    public static String handleException(Throwable e) {
        String errorMsg;
        int errorCode;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            errorCode = httpException.code();
            switch (httpException.code()) {
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    errorMsg = StringUtil.getStringById(R.string.net_error) + e.getMessage();
                    break;
            }
            return errorMsg + "\n" + StringUtil.getStringById(R.string.code_error) + errorCode;
        } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
            return StringUtil.getStringById(R.string.analys_error) + e.getMessage();
        } else if (e instanceof ConnectException) {
            return StringUtil.getStringById(R.string.connect_error) + e.getMessage();
        } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
            return StringUtil.getStringById(R.string.ssl_error) + e.getMessage();
        } else if (e instanceof ConnectTimeoutException) {
            return StringUtil.getStringById(R.string.time_out_error) + e.getMessage();
        } else if (e instanceof java.net.SocketTimeoutException) {
            return StringUtil.getStringById(R.string.time_out_error) + e.getMessage();
        } else {
            return StringUtil.getStringById(R.string.unknown_error) + e.getMessage();
        }
    }


}
